import { defineStore } from 'pinia'
import axios from 'axios'
import { getConversationByChatId, getConversationsByUserId } from '@/api/chatController.ts'
import { message } from 'ant-design-vue'

function genChatId() {
  return Date.now().toString(36) + Math.random().toString(36).slice(2, 10)
}

export const useChatSessionsStore = defineStore('chatSessions', {
  state: () => ({
    sessions: [] as Array<{
      chatId: string
      title: string
      messages: Array<{ role: 'user' | 'ai', content: string }>
    }>,
    activeChatId: '' as string,
    apiBaseUrl: import.meta.env.VITE_API_URL,
    HomeQuery: '' as string
  }),
  actions: {
    createSession(title = '新会话') {
      const chatId = genChatId()
      this.sessions.push({
        chatId,
        title,
        messages: []
      })
      this.activeChatId = chatId
      return chatId
    },
    async setActive(chatId: string) {
      this.activeChatId = chatId
      // 如果当前会话还没有加载过消息，则从后端加载
      const session = this.sessions.find(s => s.chatId === chatId)
      console.log('session', session)
      if (session && session.messages.length === 1) {
        try {
          const res = await getConversationByChatId({ chatId })
          console.log('res', res)
          if (res.data.code === 0) {
            // 将后端返回的消息列表映射到前端格式
            session.messages = res.data.data.map((msg: any) => ({
              role: msg.messageType === "USER" ? 'user' : 'ai',
              content: msg.text
            }))
          } else {
            message.error('加载会话失败')
          }
        } catch (err) {
          message.error('网络错误，加载会话失败')
        }
      }
    },
    addMessage(chatId: string, message: { role: 'user' | 'ai', content: string }) {
      const session = this.sessions.find(s => s.chatId === chatId)
      if (session) session.messages.push(message)
    },
    getActiveSession() {
      return this.sessions.find(s => s.chatId === this.activeChatId)
    },
    async loadConversations() {
      const res = await getConversationsByUserId()
      // console.log('22222222222', res.data)
      if (res.data.code == 0) {
        console.log(res.data.data)
        this.sessions = res.data.data.map(
          session => {
            return {
              chatId: session.chatId,
              title: session.chatName,
              messages: [{
                role: 'user',
                content: session.message
              }],
            }
          }
        )
      } else {
        message.error('获取历史记录失败')
      }
    }
  },
  persist: true
})
